<route lang="json5">
{
  style: {
    navigationBarTitleText: '登录',
    navigationStyle: 'custom',
  },
}
</route>

<template>
  <view class="login-container p-4">
    <view class="logo-box text-center mt-8 mb-12">
      <image src="/static/logo.jpg" class="w-70 h-25 inline-block" />
      <view class="text-2xl font-bold mt-4">4G门禁管理系统</view>
    </view>

    <wd-form :model="formData" :rules="rules" ref="loginForm">
      <wd-form-item prop="phone" label="手机号">
        <wd-input
          v-model="formData.phone"
          placeholder="请输入手机号"
          clearable
          type="number"
          :maxlength="11"
        />
      </wd-form-item>

      <wd-form-item prop="password" label="密码">
        <wd-input
          v-model="formData.password"
          placeholder="请输入密码"
          clearable
          :show-password="true"
        />
      </wd-form-item>
    </wd-form>

    <view class="mt-8">
      <wd-button type="primary" block @click="handleLogin" :loading="loading">登录</wd-button>
    </view>
  </view>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { useUserStore } from '@/store'
import { loginAPI, getUserCommunitiesAPI } from '@/service/iam'
import { decodeToken } from '@/utils/token'
import { FormRules } from 'wot-design-uni/components/wd-form/types'

const userStore = useUserStore()
const loading = ref(false)

const formData = ref({
  phone: '',
  password: '',
})

const rules: FormRules = {
  phone: [
    { required: true, message: '请输入手机号' },
    // { pattern: /^1[3-9]\d{9}$/, message: '手机号格式不正确' },
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { required: true, min: 6, max: 20, message: '密码长度为6-20位', trigger: 'blur' },
  ],
} as const

const loginForm = ref<any>()

// 检查 localStorage 中是否有账号密码，如果有则自动填写
onMounted(() => {
  const savedPhone = uni.getStorageSync('phone')
  const savedPassword = uni.getStorageSync('password')
  if (savedPhone && savedPassword) {
    formData.value.phone = savedPhone
    formData.value.password = savedPassword
    handleLogin() // 自动尝试登录
  }
})

const handleLogin = async () => {
  try {
    await loginForm.value?.validate()
    loading.value = true

    const res = await loginAPI({
      username: formData.value.phone,
      password: formData.value.password,
    })
    console.log(res)

    if (res.code === 200) {
      // 存储 token
      const token = res.data?.accessToken
      const refreshToken = res.data?.refreshToken

      uni.setStorageSync('token', token)
      uni.setStorageSync('refreshToken', refreshToken)

      // 存储账号密码到 localStorage
      uni.setStorageSync('phone', formData.value.phone)
      uni.setStorageSync('password', formData.value.password)

      // 解析 token 获取用户信息
      const tokenInfo = decodeToken(token)
      if (tokenInfo !== null) {
        // 存储用户基本信息到 store
        userStore.setUserInfo(tokenInfo as any)
      }
      console.log(tokenInfo)

      // 获取用户社区列表
      const userRes = tokenInfo.communities
      if (userRes !== null) {
        const communities = userRes

        if (communities.length === 0) {
          uni.showToast({
            title: '您暂无可访问的小区',
            icon: 'none',
          })
          userStore.clearUserInfo()
        } else if (communities.length === 1) {
          // 只有一个小区时直接进入首页
          userStore.setCurrentCommunity(communities[0])
          uni.reLaunch({
            url: '/pages/index/index',
          })
        } else {
          // 多个小区时跳转到选择小区页面
          uni.redirectTo({
            url: '/pages/login/select-community',
          })
        }
      }
      //  else {
      // 	uni.showToast({
      // 		title: '您暂无可访问的小区',
      // 		icon: 'none',
      // 	})
      // }
    }else  if (res.code === 401) {
		uni.removeStorageSync('phone')
		uni.showToast({
			title: '登录失败',
			icon: 'none',
		})
	}
  } catch (error) {
    console.error('登录失败:', error)
	uni.removeStorageSync('password')
    uni.showToast({
      title: '登录失败',
      icon: 'error',
    })
  } finally {
    loading.value = false
  }
}

const goToRegister = () => {
  uni.navigateTo({
    url: '/pages/login/register',
  })
}
</script>

<style lang="scss" scoped>
.login-container {
  min-height: 100vh;
  background-color: #f8f8f8;
}
</style>
